/*
 * Title: 矩阵链乘（Matrix Chain Multiplication）
 * Author: Yuanshun L
 * Created : 22-otc-2021
 */


#include<iostream>
#include<cstdio>
#include<stack>
#include<string>
using namespace std;

struct Matrix{
    int x,y;
    Matrix(int x=0,int y=0):x(x),y(y){}
} mx[26+1];

int main(){

    freopen("data.in","r",stdin);
    freopen("data.out","w",stdout);

    int n;
    string s;
    cin >> n;
    while(n--){
        cin >> s;
        cin >> mx[s[0]-'A'].x;
        cin >> mx[s[0]-'A'].y;
    }


    while(cin>>s){
        stack<Matrix> stk;

        int mul=0;
        int size = s.length();
        bool error = false;
        for(int i=0;i<size;i++){
            if(s[i]==')'){
                Matrix m2 = stk.top();stk.pop();
                Matrix m1 = stk.top();stk.pop();
                if(m1.y != m2.x){
                    error = true; break;
                }
                mul += m1.x * m1.y * m2.y;
                stk.push(Matrix(m1.x,m2.y));
            }
            if(isalpha(s[i])){
                stk.push(mx[s[i]-'A']);
            }
        }// for

        if(error) cout<<"error\n";
        else {
            cout<<mul<<endl;
        }
    }


    return 0;
}
